/*
 * Copyright [2019] No Copyright is Claimed
 * This is an OpenSSL-compatible implementation of the RSA Data Security, Inc.
 * MD5 Message-Digest Algorithm (RFC 1321).
 *
 * Author:
 * Alexander Peslyak, better known as Solar Designer <solar at openwall.com>
 *
 * This software was written by Alexander Peslyak in 2001.  No copyright is
 * claimed, and the software is hereby placed in the public domain.
 * In case this attempt to disclaim copyright and place the software in the
 * public domain is deemed null and void, then the software is
 * Copyright (c) 2001 Alexander Peslyak and it is hereby released to the
 * general public under the following terms:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted.
 *
 * There's ABSOLUTELY NO WARRANTY, express or implied.
 *
 * (This is a heavily cut-down "BSD license".)
 *
 * This differs from Colin Plumb's older public domain implementation in that
 * no exactly 32-bit integer data type is required (any 32-bit or wider
 * unsigned integer data type will do), there's no compile-time endianness
 * configuration, and the function prototypes match OpenSSL's.  No code from
 * Colin Plumb's implementation has been reused; this comment merely compares
 * the properties of the two independent implementations.
 *
 * The primary goals of this implementation are portability and ease of use.
 * It is meant to be fast, but not as fast as possible.  Some known
 * optimizations are not included to reduce source code size and avoid
 * compile-time configuration.
 */
// Homepage:
// http://openwall.info/wiki/people/solar/software/public-domain-source-code/md5

#include <cstring>
#include <cstdio>
#include <iterator>

#include "md5.h"

namespace MD5Test {
/*
 * The basic MD5 functions.
 *
 * F and MD5G are optimized compared to their RFC 1321 definitions for
 * architectures that lack an AND-NOT instruction, just like in Colin Plumb's
 * implementation.
 */

static uint32_t md5_f(uint32_t in_x, uint32_t in_y, uint32_t in_z) {
    return (in_z ^ (in_x & (in_y ^ in_z)));
}

static uint32_t md5_g(uint32_t in_x, uint32_t in_y, uint32_t in_z) {
    return (in_y) ^ ((in_z) & ((in_x) ^ (in_y)));
}

static uint32_t md5_h(uint32_t in_x, uint32_t in_y, uint32_t in_z) {
    return (((in_x) ^ (in_y)) ^ (in_z));
}

static uint32_t md5_h2(uint32_t in_x, uint32_t in_y, uint32_t in_z) {
    return ((in_x) ^ ((in_y) ^ (in_z)));
}

static uint32_t md5_i(uint32_t in_x, uint32_t in_y, uint32_t in_z) {
    return ((in_y) ^ ((in_x) | ~(in_z)));
}

typedef uint32_t (*StepFunctionType)(uint32_t in_x, uint32_t in_y, uint32_t in_z);
static void md5_step(const StepFunctionType in_step_function_type, uint32_t &in_a, uint32_t in_b, uint32_t in_c,
                 uint32_t in_d, uint32_t in_x, uint32_t in_t, uint32_t in_s) {
  in_a += in_step_function_type(in_b, in_c, in_d) + in_x + in_t;
  in_a = ((in_a << in_s) | ((in_a & 0xffffffffU) >> (32 - in_s)));
  in_a += in_b;
}

/*
 * SET reads 4 input bytes in little-endian byte order and stores them in a
 * properly aligned word in host byte order.
 *
 * The check for little-endian architectures that tolerate unaligned memory
 * accesses is just an optimization.  Nothing will break if it fails to detect
 * a suitable architecture.
 *
 * Unfortunately, this optimization may be a C strict aliasing rules violation
 * if the caller's data buffer has effective type that cannot be aliased by
 * MD5_u32plus.  In practice, this problem may occur if these MD5 routines are
 * inlined into a calling function, or with future and dangerously advanced
 * link-time optimizations.  For the time being, keeping these MD5 routines in
 * their own translation unit avoids the problem.
 */
#if defined(__i386__) || defined(__x86_64__) || defined(__vax__)
static uint32_t md5_set(const uint8_t *const para_ptr, uint32_t in_n) {
  return *(uint8_to_uint32(std::next(para_ptr, static_cast<int64_t>(in_n) * 4)));
}

static uint32_t md5_get(const uint8_t *const para_ptr, uint32_t in_n) {
  return md5_set(para_ptr, in_n);
}

#else

static uint32_t md5_set(const uint8_t *const para_ptr, uint32_t in_n) {
  return *((const uint32_t *)(&para_ptr[in_n * 4]));
}

static uint32_t md5_get(const uint8_t *const para_ptr, uint32_t in_n) {
  return md5_set(para_ptr, in_n);
}
#endif

/*
 * This processes one or more 64-byte data blocks, but does NOT update the bit
 * counters.  There are no alignment requirements.
 */
static const void* body(Md5Ctx &ctx, const void *const in_data, uint64_t in_size) {
  const uint8_t *para_ptr;
  uint32_t para_a = ctx.md5_ctx_a;
  uint32_t para_b = ctx.md5_ctx_b;
  uint32_t para_c = ctx.md5_ctx_c;
  uint32_t para_d = ctx.md5_ctx_d;
  uint32_t saved_a{0};
  uint32_t saved_b{0};
  uint32_t saved_c{0};
  uint32_t saved_d{0};

  para_ptr = reinterpret_cast<const uint8_t *>(in_data);

  do {
    saved_a = para_a;
    saved_b = para_b;
    saved_c = para_c;
    saved_d = para_d;

    /* Round 1 */
    md5_step(&md5_f, para_a, para_b, para_c, para_d, md5_set(para_ptr, 0), 0xd76aa478U, 7);
    md5_step(&md5_f, para_d, para_a, para_b, para_c, md5_set(para_ptr, 1), 0xe8c7b756U, 12);
    md5_step(&md5_f, para_c, para_d, para_a, para_b, md5_set(para_ptr, 2), 0x242070dbU, 17);
    md5_step(&md5_f, para_b, para_c, para_d, para_a, md5_set(para_ptr, 3), 0xc1bdceeeU, 22);
    md5_step(&md5_f, para_a, para_b, para_c, para_d, md5_set(para_ptr, 4), 0xf57c0fafU, 7);
    md5_step(&md5_f, para_d, para_a, para_b, para_c, md5_set(para_ptr, 5), 0x4787c62aU, 12);
    md5_step(&md5_f, para_c, para_d, para_a, para_b, md5_set(para_ptr, 6), 0xa8304613U, 17);
    md5_step(&md5_f, para_b, para_c, para_d, para_a, md5_set(para_ptr, 7), 0xfd469501U, 22);
    md5_step(&md5_f, para_a, para_b, para_c, para_d, md5_set(para_ptr, 8), 0x698098d8U, 7);
    md5_step(&md5_f, para_d, para_a, para_b, para_c, md5_set(para_ptr, 9), 0x8b44f7afU, 12);
    md5_step(&md5_f, para_c, para_d, para_a, para_b, md5_set(para_ptr, 10), 0xffff5bb1U, 17);
    md5_step(&md5_f, para_b, para_c, para_d, para_a, md5_set(para_ptr, 11), 0x895cd7beU, 22);
    md5_step(&md5_f, para_a, para_b, para_c, para_d, md5_set(para_ptr, 12), 0x6b901122U, 7);
    md5_step(&md5_f, para_d, para_a, para_b, para_c, md5_set(para_ptr, 13), 0xfd987193U, 12);
    md5_step(&md5_f, para_c, para_d, para_a, para_b, md5_set(para_ptr, 14), 0xa679438eU, 17);
    md5_step(&md5_f, para_b, para_c, para_d, para_a, md5_set(para_ptr, 15), 0x49b40821U, 22);

    /* Round 2 */
    md5_step(&md5_g, para_a, para_b, para_c, para_d, md5_get(para_ptr, 1), 0xf61e2562U, 5);
    md5_step(&md5_g, para_d, para_a, para_b, para_c, md5_get(para_ptr, 6), 0xc040b340U, 9);
    md5_step(&md5_g, para_c, para_d, para_a, para_b, md5_get(para_ptr, 11), 0x265e5a51U, 14);
    md5_step(&md5_g, para_b, para_c, para_d, para_a, md5_get(para_ptr, 0), 0xe9b6c7aaU, 20);
    md5_step(&md5_g, para_a, para_b, para_c, para_d, md5_get(para_ptr, 5), 0xd62f105dU, 5);
    md5_step(&md5_g, para_d, para_a, para_b, para_c, md5_get(para_ptr, 10), 0x02441453U, 9);
    md5_step(&md5_g, para_c, para_d, para_a, para_b, md5_get(para_ptr, 15), 0xd8a1e681U, 14);
    md5_step(&md5_g, para_b, para_c, para_d, para_a, md5_get(para_ptr, 4), 0xe7d3fbc8U, 20);
    md5_step(&md5_g, para_a, para_b, para_c, para_d, md5_get(para_ptr, 9), 0x21e1cde6U, 5);
    md5_step(&md5_g, para_d, para_a, para_b, para_c, md5_get(para_ptr, 14), 0xc33707d6U, 9);
    md5_step(&md5_g, para_c, para_d, para_a, para_b, md5_get(para_ptr, 3), 0xf4d50d87U, 14);
    md5_step(&md5_g, para_b, para_c, para_d, para_a, md5_get(para_ptr, 8), 0x455a14edU, 20);
    md5_step(&md5_g, para_a, para_b, para_c, para_d, md5_get(para_ptr, 13), 0xa9e3e905U, 5);
    md5_step(&md5_g, para_d, para_a, para_b, para_c, md5_get(para_ptr, 2), 0xfcefa3f8U, 9);
    md5_step(&md5_g, para_c, para_d, para_a, para_b, md5_get(para_ptr, 7), 0x676f02d9U, 14);
    md5_step(&md5_g, para_b, para_c, para_d, para_a, md5_get(para_ptr, 12), 0x8d2a4c8aU, 20);

    /* Round 3 */
    md5_step(&md5_h, para_a, para_b, para_c, para_d, md5_get(para_ptr, 5), 0xfffa3942U, 4);
    md5_step(&md5_h2, para_d, para_a, para_b, para_c, md5_get(para_ptr, 8), 0x8771f681U, 11);
    md5_step(&md5_h, para_c, para_d, para_a, para_b, md5_get(para_ptr, 11), 0x6d9d6122U, 16);
    md5_step(&md5_h2, para_b, para_c, para_d, para_a, md5_get(para_ptr, 14), 0xfde5380cU, 23);
    md5_step(&md5_h, para_a, para_b, para_c, para_d, md5_get(para_ptr, 1), 0xa4beea44U, 4);
    md5_step(&md5_h2, para_d, para_a, para_b, para_c, md5_get(para_ptr, 4), 0x4bdecfa9U, 11);
    md5_step(&md5_h, para_c, para_d, para_a, para_b, md5_get(para_ptr, 7), 0xf6bb4b60U, 16);
    md5_step(&md5_h2, para_b, para_c, para_d, para_a, md5_get(para_ptr, 10), 0xbebfbc70U, 23);
    md5_step(&md5_h, para_a, para_b, para_c, para_d, md5_get(para_ptr, 13), 0x289b7ec6U, 4);
    md5_step(&md5_h2, para_d, para_a, para_b, para_c, md5_get(para_ptr, 0), 0xeaa127faU, 11);
    md5_step(&md5_h, para_c, para_d, para_a, para_b, md5_get(para_ptr, 3), 0xd4ef3085U, 16);
    md5_step(&md5_h2, para_b, para_c, para_d, para_a, md5_get(para_ptr, 6), 0x04881d05U, 23);
    md5_step(&md5_h, para_a, para_b, para_c, para_d, md5_get(para_ptr, 9), 0xd9d4d039U, 4);
    md5_step(&md5_h2, para_d, para_a, para_b, para_c, md5_get(para_ptr, 12), 0xe6db99e5U, 11);
    md5_step(&md5_h, para_c, para_d, para_a, para_b, md5_get(para_ptr, 15), 0x1fa27cf8U, 16);
    md5_step(&md5_h2, para_b, para_c, para_d, para_a, md5_get(para_ptr, 2), 0xc4ac5665U, 23);

    /* Round 4 */
    md5_step(&md5_i, para_a, para_b, para_c, para_d, md5_get(para_ptr, 0), 0xf4292244U, 6);
    md5_step(&md5_i, para_d, para_a, para_b, para_c, md5_get(para_ptr, 7), 0x432aff97U, 10);
    md5_step(&md5_i, para_c, para_d, para_a, para_b, md5_get(para_ptr, 14), 0xab9423a7U, 15);
    md5_step(&md5_i, para_b, para_c, para_d, para_a, md5_get(para_ptr, 5), 0xfc93a039U, 21);
    md5_step(&md5_i, para_a, para_b, para_c, para_d, md5_get(para_ptr, 12), 0x655b59c3U, 6);
    md5_step(&md5_i, para_d, para_a, para_b, para_c, md5_get(para_ptr, 3), 0x8f0ccc92U, 10);
    md5_step(&md5_i, para_c, para_d, para_a, para_b, md5_get(para_ptr, 10), 0xffeff47dU, 15);
    md5_step(&md5_i, para_b, para_c, para_d, para_a, md5_get(para_ptr, 1), 0x85845dd1U, 21);
    md5_step(&md5_i, para_a, para_b, para_c, para_d, md5_get(para_ptr, 8), 0x6fa87e4fU, 6);
    md5_step(&md5_i, para_d, para_a, para_b, para_c, md5_get(para_ptr, 15), 0xfe2ce6e0U, 10);
    md5_step(&md5_i, para_c, para_d, para_a, para_b, md5_get(para_ptr, 6), 0xa3014314U, 15);
    md5_step(&md5_i, para_b, para_c, para_d, para_a, md5_get(para_ptr, 13), 0x4e0811a1U, 21);
    md5_step(&md5_i, para_a, para_b, para_c, para_d, md5_get(para_ptr, 4), 0xf7537e82U, 6);
    md5_step(&md5_i, para_d, para_a, para_b, para_c, md5_get(para_ptr, 11), 0xbd3af235U, 10);
    md5_step(&md5_i, para_c, para_d, para_a, para_b, md5_get(para_ptr, 2), 0x2ad7d2bbU, 15);
    md5_step(&md5_i, para_b, para_c, para_d, para_a, md5_get(para_ptr, 9), 0xeb86d391U, 21);

    para_a += saved_a;
    para_b += saved_b;
    para_c += saved_c;
    para_d += saved_d;

    para_ptr = std::next(para_ptr, 64L);
    in_size -= 64;
  } while (in_size != 0);

  ctx.md5_ctx_a = para_a;
  ctx.md5_ctx_b = para_b;
  ctx.md5_ctx_c = para_c;
  ctx.md5_ctx_d = para_d;

  return para_ptr;
}

void md5_init(Md5Ctx &out_ctx) {
  out_ctx.md5_ctx_a = 0x67452301U;
  out_ctx.md5_ctx_b = 0xefcdab89U;
  out_ctx.md5_ctx_c = 0x98badcfeU;
  out_ctx.md5_ctx_d = 0x10325476U;

  out_ctx.md5_ctx_lo = 0;
  out_ctx.md5_ctx_hi = 0;
}

void md5_update(Md5Ctx &out_ctx, const void *origin_data, uint64_t in_size) {
  uint32_t saved_lo{0};
  bool go_on = true;
  saved_lo = out_ctx.md5_ctx_lo;
  out_ctx.md5_ctx_lo = static_cast<uint32_t>(saved_lo + in_size) & 0x1fffffffU;
  if (out_ctx.md5_ctx_lo < saved_lo) {
    out_ctx.md5_ctx_hi++;
  }
  out_ctx.md5_ctx_hi += static_cast<uint32_t>(in_size >> 29);

  const uint64_t used = static_cast<uint64_t>(saved_lo) & 0x3fU;

  if (used != 0) {
    const uint64_t available = 64U - used;

    if (in_size < available) {
      memcpy(&out_ctx.md5_ctx_buffer[used], origin_data, in_size);
      go_on = false;
    }
    if (go_on) {
      memcpy(&out_ctx.md5_ctx_buffer[used], origin_data, available);
      origin_data = std::next(reinterpret_cast<const uint8_t *>(origin_data), static_cast<int64_t>(available));
      in_size -= available;
      (void)body(out_ctx, out_ctx.md5_ctx_buffer, 64);
    }
  }
  if (go_on) {
    if (in_size >= 64) {
      origin_data = body(out_ctx, origin_data, in_size & ~static_cast<uint64_t>(0x3f));
      in_size &= 0x3fU;
    }

    memcpy(out_ctx.md5_ctx_buffer, origin_data, in_size);
  }
}

static void convert_to_bytes(uint8_t *const out_dst, uint32_t in_src) {
    *out_dst = static_cast<uint8_t>(in_src);
    *std::next(out_dst, 1L) = static_cast<uint8_t>(in_src >> 8);
    *std::next(out_dst, 2L) = static_cast<uint8_t>(in_src >> 16);
    *std::next(out_dst, 3L) = static_cast<uint8_t>(in_src >> 24);
}

void md5_final(uint8_t *const out_result, Md5Ctx &out_ctx) {
  uint64_t used{0};
  uint64_t available{0};

  used = static_cast<uint64_t>(out_ctx.md5_ctx_lo) & 0x3fU;

  out_ctx.md5_ctx_buffer[used++] = 0x80U;

  available = 64 - used;

  if (available < 8) {
    memset(&out_ctx.md5_ctx_buffer[used], 0, available);
    (void)body(out_ctx, out_ctx.md5_ctx_buffer, 64);
    used = 0;
    available = 64;
  }

  memset(&out_ctx.md5_ctx_buffer[used], 0, available - 8);

  out_ctx.md5_ctx_lo <<= 3;
  convert_to_bytes(&out_ctx.md5_ctx_buffer[56], out_ctx.md5_ctx_lo);
  convert_to_bytes(&out_ctx.md5_ctx_buffer[60], out_ctx.md5_ctx_hi);

  (void)body(out_ctx, out_ctx.md5_ctx_buffer, 64);

  convert_to_bytes(out_result, out_ctx.md5_ctx_a);
  convert_to_bytes(std::next(out_result, 4L), out_ctx.md5_ctx_b);
  convert_to_bytes(std::next(out_result, 8L), out_ctx.md5_ctx_c);
  convert_to_bytes(std::next(out_result, 12L), out_ctx.md5_ctx_d);

  memset(&out_ctx, 0, sizeof(out_ctx));
}

void md5_print(uint8_t* const out_buf, const uint8_t* const in_result, uint64_t in_len) {
    for (uint32_t loop_i = 0; loop_i < KMd5ResultSize; ++loop_i) {
        char* out_ptr = reinterpret_cast<char*>(out_buf) + loop_i * 2;
        (void)snprintf(out_ptr, in_len - loop_i * 2, "%02x",
            static_cast<uint32_t>(in_result[loop_i]));
    }
    out_buf[in_len * 2] = '\0';
}
}  // namespace MD5Test
